import './index.less'

import React, { useEffect, useRef, useState } from 'react'
import { LdhPage, LdhPageBody } from '@biz/PageCompnents'
import AForm from '@/components/AForm'
import { Input, Form } from 'antd'
import {
  onPostThirdCouponAddXhr,
  onGetThirdCouponDetailXhr,
  onPostThirdCouponEditXhr,
  onGetThirdCouponShopListXhr,
} from '@/api/coupon'
import AToast from '@/components/AToast'
import { useNavigate, useSearchParams } from 'react-router-dom'
// import { detailMock } from './mock' // mock数据

const AddThirdCoupon = () => {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams() // 获取查询参数
  const id = searchParams.get('id')
  const type = searchParams.get('type')
  const [detail, setDetail] = useState(null)
  const preMessage = id ? '编辑三方优惠券' : '添加三方优惠券'
  const [selftData, setSelfData] = useState([
    {
      couponId: '',
      quantity: '',
    },
  ])
  const [sectionlist, setSectionlist] = useState([]) // 表单配置

  // 修改初始化 channel 的方式
  const [channel, setChannel] = useState(1) // 渠道
  const [isFirstLoad, setIsFirstLoad] = useState(true)

  const [keyword, setKeyword] = useState('')
  const [shopListOptions, setShopListOptions] = useState([]) // 店铺下拉
  const formRef = useRef(null)

  useEffect(() => {
    setSectionlist([
      {
        type: 'radio',
        label: '渠道',
        name: 'channel',
        rules: [
          {
            required: true,
            message: '请选择渠道',
          },
        ],
        options: [
          {
            label: '美团',
            value: 1,
            defaultChecked: true,
          },
          {
            label: '点评',
            value: 2,
          },
          {
            label: '抖音',
            value: 3,
          },
        ],
        itemEvents: {
          onChange: (e) => {
            setChannel(e.target.value)
          },
        },
      },
      {
        type: 'select',
        label: '适用门店',
        name: 'thirdShopId',
        rules: [
          {
            required: true,
            message: '请选择适用门店',
          },
        ],
        maxLength: 60,
        itemProps: {
          placeholder: '请选择适用门店',
          showSearch: true,
          allowClear: true,
          options: shopListOptions,
        },
        itemEvents: {
          onSearch: (value) => {
            setKeyword(value)
          },
        },
      },
      {
        label: '团购ID',
        name: 'groupProductId',
        rules: [
          {
            required: true,
            message: '请输入团购ID',
          },
        ],
        maxLength: 60,
      },
      {
        label: '团购名称',
        name: 'name',
        rules: [
          {
            required: true,
            message: '请输入团购名称',
          },
        ],
        maxLength: 60,
      },
      // {
      //   label: '团购售价',
      //   name: 'salePrice',
      //   rules: [
      //     {
      //       required: true,
      //       message: '请输入团购售价',
      //     },
      //   ],
      // },
      {
        type: 'self',
        label: '',
        selftComponent: ({ form }) => {
          if (!selftData || !Array.isArray(selftData)) return
          return (
            <Form.Item
              labelCol={{ flex: '120px' }}
              wrapperCol={{ flex: 1 }}
              label="关联券ID"
              required={type !== 'detail'}
              name="couponThirdRelList"
              rules={[
                {
                  validator: async (_, value) => {
                    if (!value || value.length === 0) {
                      throw new Error('请至少添加一条关联券信息')
                    }
                  },
                },
              ]}
            >
              <Form.List>
                {() => {
                  return selftData?.map((item, index) => (
                    <Form.Item>
                      <div
                        className="self-input-box-item"
                        key={index}
                        labelAlign="right"
                      >
                        {type !== 'detail' ? (
                          <Input
                            className="self-input"
                            placeholder="输入优惠券 ID"
                            size="large"
                            value={item?.couponId}
                            onChange={(e) => {
                              const newData = [...selftData]
                              newData[index] = {
                                ...newData[index],
                                couponId: e.target.value,
                              }
                              setSelfData(newData)
                              form.setFields([
                                {
                                  name: 'couponThirdRelList',
                                  value: newData,
                                  touched: true,
                                },
                              ])
                            }}
                          />
                        ) : (
                          <div style={{ marginTop: '10px' }}>
                            id：{item?.couponId}
                          </div>
                        )}
                        {type !== 'detail' ? (
                          <Input
                            className="self-input"
                            placeholder="输入数量"
                            size="large"
                            value={item?.quantity}
                            onChange={(e) => {
                              const newData = [...selftData]
                              newData[index] = {
                                ...newData[index],
                                quantity: e.target.value,
                              }
                              setSelfData(newData)
                              form.setFields([
                                {
                                  name: 'couponThirdRelList',
                                  value: newData,
                                  touched: true,
                                },
                              ])
                            }}
                          />
                        ) : (
                          <div
                            style={{ marginLeft: '16px', marginTop: '10px' }}
                          >
                            数量：{item?.quantity}
                          </div>
                        )}
                        <div
                          className="delete"
                          onClick={() => {
                            if (selftData?.length > 1) {
                              const newData = [...selftData]
                              newData.splice(index, 1)
                              setSelfData(newData)
                              form.setFields([
                                {
                                  name: 'couponThirdRelList',
                                  value: newData,
                                  touched: true,
                                },
                              ])
                            }
                          }}
                        >
                          {selftData?.length > 1 &&
                          index === selftData?.length - 1 &&
                          type !== 'detail'
                            ? ' 删除'
                            : ''}
                        </div>
                      </div>
                    </Form.Item>
                  ))
                }}
              </Form.List>
              {type !== 'detail' && (
                <div
                  className="add"
                  onClick={() => {
                    setSelfData((pre) => {
                      return [
                        ...pre,
                        {
                          couponId: '',
                          quantity: '',
                        },
                      ]
                    })
                  }}
                >
                  + 添加
                </div>
              )}
            </Form.Item>
          )
        },
      },
    ])
  }, [selftData, shopListOptions])
  const onSubmit = async (formData) => {
    const xhr = id ? onPostThirdCouponEditXhr : onPostThirdCouponAddXhr
    const params = id ? { ...formData, id } : formData
    try {
      const res = await xhr(params)
      if (res?.success) {
        AToast.success(`${preMessage}成功`)
        setTimeout(() => {
          navigate(`/page/product/thirdCoupon`)
        }, 1200)
      } else {
        AToast.error(`${preMessage}失败: ${res?.message}`)
      }
    } catch (e) {
      AToast.error(`${preMessage}失败: ${e}`)
    }
  }

  // 获取优惠券详情
  const getCouponDetail = async (id) => {
    if (!id) return
    try {
      const res = await onGetThirdCouponDetailXhr({ id: id })
      if (res?.success) {
        setDetail(res?.vo)
        setSelfData(
          res?.vo?.couponThirdRelList?.length < 1
            ? [{ couponId: '', quantity: '' }]
            : res?.vo?.couponThirdRelList
        )
        // 在这里直接设置 channel 并请求店铺列表
        if (res?.vo?.channel) {
          setChannel(res?.vo?.channel)
          getThirdShopList(res?.vo?.channel)
        }
      }
    } catch (e) {
      console.log('获取优惠券详情失败' + e)
    }
  }

  // 获取三方店铺下拉选项
  const getThirdShopList = async (currentChannel) => {
    const params = keyword
      ? {
          keyword: keyword,
          thirdChannel: currentChannel,
        }
      : {
          thirdChannel: currentChannel,
        }
    try {
      const res = await onGetThirdCouponShopListXhr({ ...params })
      if (res?.success) {
        setShopListOptions(res?.vo?.optionList || [])
      }
    } catch (e) {
      console.log('获取三方店铺下拉选项失败' + e)
    }
  }

  useEffect(() => {
    if (!id) return
    getCouponDetail(id)
  }, [id])

  // 合并处理 channel 变化和初始加载
  // 修改这个 effect，只处理非编辑状态和手动切换的情况
  useEffect(() => {
    if (!id || !isFirstLoad) {
      getThirdShopList(channel)
    }
  }, [channel, keyword])

  return (
    <LdhPage
      className="verification-page"
      title={type !== 'detail' ? preMessage : '三方优惠券详情'}
    >
      <LdhPageBody>
        <AForm
          ref={formRef}
          title="产品配置"
          sectionlist={sectionlist}
          onSubmit={onSubmit}
          detail={detail}
          type={type}
        />
      </LdhPageBody>
    </LdhPage>
  )
}
export default AddThirdCoupon
